/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the GPL
 * version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.prefs;

import org.digitalsoul.switchplugin.model.Configuration;
import org.digitalsoul.switchplugin.prefs.util.SetConfigurator;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

public class SwitchSetPreferencesPage extends PreferencePage implements IWorkbenchPreferencePage {

    private Composite mainPanel;
    private SetConfigurator configurator;

    @Override
    protected Control createContents(Composite parent) {
        noDefaultAndApplyButton();
        mainPanel = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout(2, false);
        layout.marginRight = 12;
        mainPanel.setLayout(layout);
        new SwitchSetListUI(configurator).build(mainPanel);
        return mainPanel;
    }

    @Override
    public boolean performOk() {
        save();
        return true;
    }

    @Override
    protected void performApply() {
        save();
    }

    private void save() {
        Preferences.save(configurator.getConfiguration());
    }

    public void init(IWorkbench workbench) {
        initializeConfigurator(Preferences.load());
    }

    private void initializeConfigurator(Configuration configuration) {
        if (configurator == null) {
            configurator = new SetConfigurator(configuration);
        }
    }
}
